package gui;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import net.proteanit.sql.DbUtils;
import codes.DBBean;

public class Category extends javax.swing.JFrame {
	
	 String queryDelete;
	 String queryUpdate;
	 public static String nameUpdate;
	 public static String keywordsUpdate;
	 public static String idParentUpdate;
	 public static String titleWebPageUpdate;
	 public static String idCategoryUpdate;
	
	public Category() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
	        initComponents();
	    }

	   
	                      
	    private void initComponents() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

	        jLabel1 = new javax.swing.JLabel();
	        jScrollPane1 = new javax.swing.JScrollPane();
	        jTable1 = new javax.swing.JTable();
	        exitButton = new javax.swing.JButton();
	        updateButton = new javax.swing.JButton();
	        deleteButton = new javax.swing.JButton();
	        insertButton = new javax.swing.JButton();
	        returnButton = new javax.swing.JButton();
	        keywordsButton = new javax.swing.JButton();
	     

	        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

	        jLabel1.setText("Category");

	        jTable1.setModel(new javax.swing.table.DefaultTableModel(
	            new Object [][] {
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null},
	                {null, null, null, null}
	            },
	            new String [] {
	                "idCategory", "idEmployee", "name", "keywords"
	            }
	        ));
	        
	        jTable1.setRowSelectionAllowed(true);
	        
	        //jTable1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
	        jScrollPane1.setViewportView(jTable1);

	        exitButton.setText("Exit");
	        exitButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                exitButtonActionPerformed(evt);
	            }
	        });

	        updateButton.setText("Update");
	        updateButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                updateButtonActionPerformed(evt);
	            }
	        });

	        deleteButton.setText("Delete");
	        deleteButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                try {
						deleteButtonActionPerformed(evt);
					} catch (InstantiationException | IllegalAccessException
							| ClassNotFoundException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	        });

	        insertButton.setText("Insert");
	        insertButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                insertButtonActionPerformed(evt);
	            }
	        });

	        returnButton.setText("Return");
	        returnButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                returnButtonActionPerformed(evt);
	            }
	        });

	        keywordsButton.setText("List Keywords");
	        keywordsButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                keywordsButtonActionPerformed(evt);
	            }
	        });

	        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
	        getContentPane().setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(layout.createSequentialGroup()
	                        .addGap(222, 222, 222)
	                        .addComponent(jLabel1))
	                    .addGroup(layout.createSequentialGroup()
	                        .addGap(36, 36, 36)
	                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 435, javax.swing.GroupLayout.PREFERRED_SIZE))
	                    .addGroup(layout.createSequentialGroup()
	                        .addContainerGap()
	                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                            .addGroup(layout.createSequentialGroup()
	                                .addComponent(insertButton)
	                                .addGap(18, 18, 18)
	                                .addComponent(deleteButton)
	                                .addGap(15, 15, 15)
	                                .addComponent(updateButton)
	                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                                .addComponent(keywordsButton)
	                                .addGap(18, 18, 18))
	                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
	                                .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
	                                .addGap(121, 121, 121)))
	                        .addComponent(returnButton)))
	                .addContainerGap(31, Short.MAX_VALUE))
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addGap(22, 22, 22)
	                .addComponent(jLabel1)
	                .addGap(18, 18, 18)
	                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addGap(42, 42, 42)
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(keywordsButton)
	                    .addComponent(updateButton)
	                    .addComponent(deleteButton)
	                    .addComponent(insertButton)
	                    .addComponent(returnButton))
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
	                .addComponent(exitButton)
	                .addGap(33, 33, 33))
	        );

	        pack();
	        
	        DBBean db = new DBBean();
			Connection con = db.openConnection();

			String query = "SELECT * FROM Category";

			PreparedStatement statement = con.prepareStatement(query);

			ResultSet result = statement.executeQuery();

			jTable1.setModel(DbUtils.resultSetToTableModel(result));
			
			jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
				
				@Override
				public void valueChanged(ListSelectionEvent e) {
					
					int row = jTable1.getSelectedRow();
					DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
					
					try{
						idCategoryUpdate = model.getValueAt(row, 0).toString();
						nameUpdate = model.getValueAt(row, 1).toString();
						keywordsUpdate = model.getValueAt(row, 2).toString();
						idParentUpdate = model.getValueAt(row, 3).toString();
						titleWebPageUpdate = model.getValueAt(row, 4).toString();
						
					}catch (NullPointerException ex){
						nameUpdate = model.getValueAt(row, 1).toString();
						keywordsUpdate = model.getValueAt(row, 2).toString();
						idParentUpdate = "";
						titleWebPageUpdate = model.getValueAt(row, 4).toString();
					}
					
					queryDelete = "DELETE from Category WHERE idCategory = " + idCategoryUpdate;
					
					//colocar botao return and notifiacao de sucesso
				}
			});
			
			
	    }// </editor-fold>                        

	    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
	    	 System.exit(0);
	    }                                        

	    private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
	    	new UpdateCategory().setVisible(true);
	        Category.this.dispose();
	    }                                        

	    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {                                         
	    	DBBean db = new DBBean();
			Connection con = db.openConnection();

			String query = queryDelete;

			PreparedStatement statement = con.prepareStatement(query);
			boolean result = statement.execute();
			JOptionPane.showMessageDialog(null, "Row deleted! ");
	        new Category().setVisible(true);
	
	    }                                        

	    private void insertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
	    	new CategoryAdd().setVisible(true);
	        Category.this.dispose();
	    }                                        

	    private void returnButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
	        new Menu().setVisible(true);
	        Category.this.dispose();
	    }                                        

	    private void keywordsButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
	        // TODO add your handling code here:
	    }                                        

	   
	  
	    public static void main(String args[]) {
	       
	        try {
	            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
	                if ("Nimbus".equals(info.getName())) {
	                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
	                    break;
	                }
	            }
	        } catch (ClassNotFoundException ex) {
	            java.util.logging.Logger.getLogger(Category.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	        } catch (InstantiationException ex) {
	            java.util.logging.Logger.getLogger(Category.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	        } catch (IllegalAccessException ex) {
	            java.util.logging.Logger.getLogger(Category.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
	            java.util.logging.Logger.getLogger(Category.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	        }
	        //</editor-fold>

	        /* Create and display the form */
	        java.awt.EventQueue.invokeLater(new Runnable() {
	            public void run() {
	                try {
						new Category().setVisible(true);
					} catch (InstantiationException | IllegalAccessException
							| ClassNotFoundException | SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	        });
	    }

	    // Variables declaration - do not modify                     
	    private javax.swing.JButton insertButton;
	    private javax.swing.JButton deleteButton;
	    private javax.swing.JButton updateButton;
	    private javax.swing.JButton keywordsButton;
	    private javax.swing.JButton returnButton;
	    private javax.swing.JButton exitButton;
	    private javax.swing.JLabel jLabel1;
	    private javax.swing.JScrollPane jScrollPane1;
	    private javax.swing.JTable jTable1;
	    // End of variables declaration                   
	}